package mainService.services;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;

import databaseManager.connection.ConnectionManager;
import databaseManager.connection.IConnection;
import mainService.HTTPService;
import mainService.ServiceParams;
import mainService.data.IpClient;
import mainService.data.UsersConnected;

/**
 * Classe che implementa un servizio di eliminazione di un log.
 * @author Mattia Grecchi, Daniel Procop
 *
 */

public class EliminaLogService extends WriterServices implements HTTPService {
	@Override
	public ArrayList<String> getServiceResult(ServiceParams params) {
		
		

		String id_log = params.getValue("id_log");
		String query="select hours,id_task from logs where id_log= '"+id_log+"'";
		int hours = 0;
		int id_task=0;
		// Load server
		IConnection manager = new ConnectionManager();
		manager.connect();

		Connection conn = manager.getConnection();

		try {
			Statement stmt = conn.createStatement();
			ResultSet rs = stmt.executeQuery(query);
			String username="";
			while(rs.next()){
				hours=rs.getInt("hours");
				id_task=rs.getInt("id_task");
				username=rs.getString("username");
				
			}
			if((!UsersConnected.getUsersConnected().getUtente(IpClient.getSingleton().getIp()).getRuolo().equalsIgnoreCase("Project Manager"))&&(UsersConnected.getUsersConnected().getUtente(IpClient.getSingleton().getIp()).getUsername().equalsIgnoreCase(username))){
				params.addParam("file", "noPermessi.html");
				return (new HttpFileServer()).getServiceResult(params);
			}	

		} catch (SQLException e) {
			e.printStackTrace();
		}
		query="Update tasks SET worked_hours = worked_hours - "+hours+" where id_task ='"+id_task+"'";
		
		boolean var = updateDb(query);
		if (!var) {// inserimento non corretto
			params.addParam("file", "cancellazioneLogFallita.html");
		} else {
			query = "DELETE FROM logs where id_log= '" + id_log + "'";
			var=updateDb(query);
			if(!var)
				params.addParam("file", "cancellazioneLogFallita.html");
			else
				params.addParam("file", "cancellazioneLogRiuscita.html");
		}

		return (new HttpFileServer()).getServiceResult(params);
	}
}
